package entity.inte;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseData<T> {
	private Integer code;
	private String msg;
	private T data;

	public static <T> ResponseData<T> parseObject(String jsonData, Class<T> c) {
		ResponseData<T> response = JSONObject.parseObject(jsonData, ResponseData.class);
		if (response.code != 0) {
			//空对象会被解析为JSONObject，这里应该设为null，否则getData时转型会抛异常
			response.setData(null);
			// 请求失败，不再继续解析
			return response;
		}

		JSONObject jsonObject = JSON.parseObject(jsonData).getJSONObject("data");
		try {
			Method method = c.getDeclaredMethod("parseObject", String.class);
			T d = (T) method.invoke(null, jsonObject.toJSONString());
			response.setData(d);
			return response;
		} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}